import React, { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence, Reorder } from 'motion/react';
import { Button } from '../../components/ui/button';
import { Input } from '../../components/ui/input';
import { Progress } from '../../components/ui/progress';
import { DigitalHuman } from '../digitalHuman/DigitalHuman'
import { ChatBubble } from '../chat/ChatBubble';
import { 
  Mic, 
  Send, 
  PhoneOff, 
  ArrowLeft,
  Volume2,
  VolumeX 
} from 'lucide-react';

// 对话模型API配置
const CHAT_API_URL = 'https://api.siliconflow.cn/v1/chat/completions';
const CHAT_API_TOKEN = 'sk-cpdpezbgckouedwtszrgesmxeshnwskeiivcmvwfzycaadbl';
const CHAT_MODEL = 'THUDM/GLM-4-9B-0414';

// 语音模型API配置
const SPEECH_API_URL = 'https://api.siliconflow.cn/v1/audio/transcriptions';
const SPEECH_API_TOKEN = 'sk-uvldqxtojlqacnvikorauwvtwuscrvwinyeafcmfxcbobkfa';
const SPEECH_MODEL = 'FunAudioLLM/SenseVoiceSmall';

interface Message {
  id: string;
  content: string;
  type: 'user' | 'system';
  timestamp: string;
}

interface ChatPageProps {
  onEndSession: () => void;
  onGoBack: () => void;
  onProceedToRecommendation: (symptoms: string[]) => void;
}

export function ChatPage({ onEndSession, onGoBack, onProceedToRecommendation }: ChatPageProps) {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      content: '您好！我是您的智能导诊助手。请详细描述一下您的症状，我会根据您的情况为您推荐合适的科室。',
      type: 'system',
      timestamp: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
  ]);
  
  const [inputMessage, setInputMessage] = useState('');
  const [isRecording, setIsRecording] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(1);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [isVolumeOn, setIsVolumeOn] = useState(true);
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null);
  const [audioChunks, setAudioChunks] = useState<Blob[]>([]);
  
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const totalSteps = 5;
  const progress = (currentStep / totalSteps) * 100;

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const addMessage = (content: string, type: 'user' | 'system') => {
    const newMessage: Message = {
      id: Date.now().toString(),
      content,
      type,
      timestamp: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    };
    setMessages(prev => [...prev, newMessage]);
  };

  const callChatAPI = async (userMessage: string) => {
     try {
      const response = await fetch(CHAT_API_URL, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${CHAT_API_TOKEN}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: CHAT_MODEL,
          messages: [
            {
              role: "system",
              content: "你是一个专业的医疗导诊助手。你的任务是通过与用户对话收集他们的症状信息，并根据症状推荐合适的科室。请以友好、专业的态度与用户交流，逐步收集症状信息。"
            },
            ...messages.map(m => ({
              role: m.type === 'user' ? 'user' : 'assistant',
              content: m.content
            })),
            {
              role: "user",
              content: userMessage
            }
          ],
          stream: false
        })
      });

      if(!response.ok) {
        throw new Error(`Failed to fetch: ${response.status}`);
      }
      const data = await response.json();
      return data.choices[0].message.content;
    } catch(error) {
      console.error(error);
      return "抱歉，我暂时无法处理您的请求。请稍后重试。";
    }
  }

  const handleSendMessage = async () => {
    if (!inputMessage.trim()) return;

    const userMessage = inputMessage.trim();
    setInputMessage('');
    addMessage(userMessage, 'user');
    setIsLoading(true);
    
    try {
      const aiResponse = await callChatAPI(userMessage) 

      setIsLoading(false);
      setIsSpeaking(true);
      // 此处代码是为了解决大模型API返回的响应中换行符的格式问题
      const formattedResponse = aiResponse.replace(/\n+/g, '\n').trim();
      addMessage(formattedResponse, 'system');

      setTimeout(() => setIsSpeaking(false), 1000)

      if(currentStep < totalSteps) {
        setCurrentStep(prev => prev + 1)
      } else {
        setTimeout(() => {
          const symptoms = extractSymptomsFromResponse(aiResponse);
          onProceedToRecommendation(symptoms);
        }, 2000)
      }
    } catch(error) {
      console.error(error)
    }
  };

  const extractSymptomsFromResponse = (response: string) => { 
    const commonSymptoms = ['胃痛', '反酸', '腹胀', '头痛', '发热', '咳嗽'];
    return commonSymptoms.filter(symptom => response.includes(symptom));
  };

  const handleVoiceRecord = async () => {
    try {
      if(!isRecording) {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        const recorder = new MediaRecorder(stream);
        setMediaRecorder(recorder);
        setAudioChunks([]);

        recorder.ondataavailable = (event) => {
          if(event.data.size > 0) {
            setAudioChunks(prevChunks => [...prevChunks, event.data]);
          }
        };

        recorder.onstop = async () => {
          const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
          await transcribeAudio(audioBlob);
          stream.getTracks().forEach(track => track.stop());
        };

        recorder.start();
        setIsRecording(true);
      } else {
        // 停止录音
        mediaRecorder?.stop();
        setIsLoading(false);
      }
    } catch(error) {
      console.error(error)
      setIsRecording(false);
    }
  };

  const transcribeAudio = async (audioBlob: Blob) => { 
    try {
      const formData = new FormData();
      formData.append('model', SPEECH_MODEL);
      formData.append('file', audioBlob, 'recording.wav');

      const response = await fetch(SPEECH_API_URL, {
        method: 'POST',
        body: formData,
        headers: {
          Authorization: `Bearer ${SPEECH_API_TOKEN}`
        },
      })
      if (!response.ok) {
        throw new Error(`语音识别失败：${response.status}`);
      }

      const data = await response.json();
      const transcribeText = data.text;

      if(transcribeText) {
        setInputMessage(transcribeText);
      } else {
        addMessage('未能识别到语音内容，请重试', 'system');
      }
    } catch(error) {
      console.error(error)
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <div className="flex flex-col h-screen bg-gradient-to-br from-blue-50 to-white">
      {/* 顶部状态栏 */}
      <motion.div 
        className="flex-shrink-0 bg-white shadow-sm border-b px-4 py-3"
        initial={{ y: -100 }}
        animate={{ y: 0 }}
      >
        <div className="flex items-center justify-between max-w-6xl mx-auto">
          <div className="flex items-center space-x-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={onGoBack}
              className="text-gray-600"
            >
              <ArrowLeft className="w-4 h-4" />
            </Button>
            <div className="flex items-center space-x-3">
              <Progress value={progress} className="w-32" />
              <span className="text-sm text-gray-600">
                {currentStep}/{totalSteps} 症状分析中
              </span>
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsVolumeOn(!isVolumeOn)}
              className="text-gray-600"
            >
              {isVolumeOn ? <Volume2 className="w-4 h-4" /> : <VolumeX className="w-4 h-4" />}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={onEndSession}
              className="text-red-600 hover:text-red-700 hover:bg-red-50"
            >
              <PhoneOff className="w-4 h-4 mr-1" />
              结束会话
            </Button>
          </div>
        </div>
      </motion.div>

      {/* 主要内容区 */}
      <div className="flex-1 flex overflow-hidden">
        {/* 数字人区域 */}
        <motion.div 
          className="w-80 bg-gradient-to-b from-blue-50 to-white p-6 flex flex-col items-center justify-center border-r"
          initial={{ x: -100, opacity: 0 }}
          animate={{ x: 0, opacity: 1 }}
          transition={{ delay: 0.2 }}
        >
          <DigitalHuman 
            size="large" 
            emotion={isLoading ? 'thinking' : (isSpeaking ? 'happy' : 'listening')}
            isListening={isRecording}
            isSpeaking={isSpeaking}
          />
          
          <div className="mt-6 text-center">
            <p className="text-sm text-gray-600 mb-2">
              {isRecording ? '正在倾听您的症状描述...' :
               isLoading ? '正在分析您的症状...' :
               isSpeaking ? '为您详细解答中...' :
               '请描述您的症状'}
            </p>
            
            {isRecording && (
              <motion.div 
                className="text-blue-500 text-xs"
                animate={{ opacity: [0.5, 1, 0.5] }}
                transition={{ duration: 1, repeat: Infinity }}
              >
                🎤 语音转文字中...
              </motion.div>
            )}
          </div>
        </motion.div>

        {/* 对话区域 */}
        <div className="flex-1 flex flex-col">
          {/* 消息列表 */}
          <div className="flex-1 overflow-y-auto p-6 space-y-4">
            <AnimatePresence>
              {messages.map((message) => (
                <ChatBubble
                  key={message.id}
                  message={message.content}
                  type={message.type}
                  timestamp={message.timestamp}
                />
              ))}
            </AnimatePresence>
            
            {isLoading && (
              <ChatBubble
                message=""
                type="system"
                isLoading={true}
              />
            )}
            
            <div ref={messagesEndRef} />
          </div>

          {/* 输入区域 */}
          <div className="flex-shrink-0 bg-white border-t p-4">
            <div className="flex items-end space-x-3 max-w-6xl mx-auto">
              {/* 语音按钮 */}
              <Button
                variant={isRecording ? "destructive" : "outline"}
                size="lg"
                onMouseDown={handleVoiceRecord}
                className={`p-3 rounded-full transition-all duration-200 ${
                  isRecording 
                    ? 'bg-red-500 hover:bg-red-600 text-white scale-110' 
                    : 'hover:bg-blue-50 hover:border-blue-300'
                }`}
              >
                <Mic className="w-5 h-5" />
              </Button>

              {/* 文字输入框 */}
              <div className="flex-1 relative">
                <Input
                  ref={inputRef}
                  value={inputMessage}
                  onChange={(e) => setInputMessage(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="请描述您的症状，例如'最近胃痛、反酸'..."
                  className="min-h-[52px] pr-12 py-3 text-base border-2 focus:border-blue-400 resize-none rounded-xl bg-gray-50 focus:bg-white transition-all duration-200"
                  disabled={isLoading}
                />
                
                {/* 发送按钮 */}
                <Button
                  onClick={handleSendMessage}
                  disabled={!inputMessage.trim() || isLoading}
                  size="sm"
                  className="absolute right-2 top-1/2 -translate-y-1/2 bg-blue-500 hover:bg-blue-600 text-white p-2 rounded-lg disabled:opacity-50"
                >
                  <Send className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}